<template>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" :size="formSize" status-icon
        v-loading="editLoading">
        <el-form-item v-for="(column, index) in columns" :label="column.title" :prop="column.prop" :key="index">
            <el-input v-if="column.type === 'input'" v-model="ruleForm[column.key]" :placeholder="column.placeholder" />
            <!-- <el-select-v2 v-else-if="column.type === 'select'" v-model="ruleForm[column.key]" :options="column.selectOption"
                :placeholder="column.placeholder ? column.placeholder : '请选择'" filterable /> -->
            <el-select-v2 v-else-if="column.type === 'select'" :loading="selectloading" v-model="ruleForm[column.key]" filterable :remote="column.remoteUrl ? true : false" :remote-method="remoteMethod(column.remoteUrl, index)" clearable :options="column.selectOption" :placeholder="column.placeholder ? column.placeholder : '请选择'"/>
            <el-date-picker v-else-if="column.type === 'date'" v-model="ruleForm[column.key]" type="date"
                label="column.title" :placeholder="column.placeholder ? column.placeholder : '请选择'" style="width: 100%" />
            <el-switch v-else-if="column.type === 'switch'" :active-value="column.switchOpen"
                :inactive-value="column.switchClose" v-model="ruleForm[column.key]" :active-color="column.switchOpenColor"
                :inactive-color="column.switchCloseColor" :active-text="column.switchOpenText"
                :inactive-text="column.switchCloseText" />
            <el-checkbox-group v-else-if="column.type === 'check'" v-model="ruleForm[column.key]">
                <el-checkbox v-for="(option, index) in column.selectOption" :label="option.value" name="option.label"
                    :key="column.key + index" />
            </el-checkbox-group>
            <el-tree-v2 ref="treeRef" class="treeSelectClass" v-else-if="column.type === 'treeSelect'"
                :props="{ value: 'value', label: 'label', children: 'children', disabled: 'disable' }"
                :data="column.selectOption" :height="200" :key="model + column.key" show-checkbox
                :default-checked-keys="ruleForm[column.key]" :default-expanded-keys="[]" />
            <el-radio-group v-else-if="column.type === 'radio'" v-model="ruleForm[column.key]">
                <el-radio v-for="(option, index) in column.selectOption" :label="option.value"
                    :key="column.label + index" />
            </el-radio-group>
            <el-input v-else-if="column.type === 'textarea'" :autosize="{ minRows: 2, maxRows: 10 }" :show-word-limit="true"
                v-model="ruleForm[column.key]" type="textarea" />
            <div v-else-if="column.type === 'object'">
                <el-row>
                    <!-- <div class="" v-for="(item,okey) in ruleForm[column.key]" :key="'obj_key_' + okey">
                        {{item}}
                        {{okey}}:<el-input v-model="ruleForm[column.key][okey]" />
                    </div> -->
                    {{ ruleForm[column.key] }}
                    <div class="rowDis">
                        <div class="rowDis_div">
                            <div class="puting" v-for="(item, index) in inputList" :key="index">
                                <el-input style="width: 48.5%;" v-model="item.key" placeholder="键" />
                                <el-input style="width: 48.5%;" v-model="item.value" placeholder="值" />
                            </div>
                        </div>
                        <el-button type="primary" size="small" @click="addObject(column.key)" :icon="Plus"></el-button>
                        <el-button type="primary" size="small" @click="formatObject(column.key)">完成</el-button>
                    </div>
                </el-row>
            </div>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
            <el-button @click="closeEdit(ruleFormRef)">关闭</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { Plus } from '@element-plus/icons-vue'
import { reactive, ref, onMounted } from "vue"
import type { FormInstance, FormRules } from "element-plus"
import { ElTreeV2, ElSelectV2, ElLoading } from "element-plus"
import { getFormColumns, updateData, addData, getDetail, searchQuery } from "@/api/resources"

type KeyValue = {
  key: any
  value: any
};

const editLoading = ref(false)
const emits = defineEmits(["closeForm"])
const props = defineProps(["model", "formData"])
const formSize = ref("default")
const ruleFormRef = ref<FormInstance>()
const treeRef = ref()
let inputList = reactive<KeyValue[]>([])
editLoading.value = true
onMounted(() => {
    editLoading.value = false

    if (ruleForm.value.id) {
        getDetail(props.model, ruleForm.value.id).then(({ data }) => {
            ruleForm.value = data
            console.log(ruleForm.value)
        })
    }
})

const ruleForm = ref()
let columns = ref()
let rules = ref(<FormRules><unknown>[])

ruleForm.value = props.formData


getFormColumns(props.model).then(({ data, code, ext } : any) => {
    if (code === 1) {
        columns.value = data.columns
        rules.value = ext.rule
    }
})

let selectloading = ref(false)

const remoteMethod = (url: string, key: number) => {
    return (query: string) => {
        let column = columns.value[key]
        if (query !== '') {
            selectloading.value = true
            searchQuery(url, query).then((res:any)=>{
                console.log(res.data)
                selectloading.value = false
                column.selectOption = res.data.map((item :any) => {
                    return {
                        'label': item[column.optionKey],
                        'value': item[column.optionVal]
                    }
                // return item.nickname.toLowerCase().includes(query.toLowerCase())
                })
            })
        } else {
            column.selectOption = []
        }
    }
}


const submitForm = async (formEl: FormInstance | undefined) => {
    let treeSelect = columns.value.filter((column: any) => {
        console.log(column)
        return column.type == 'treeSelect'
    })
    // console.log(treeRef.value[0].getCheckedKeys(true), '--------------------------------------------------')
    // console.log('123:',treeSelect);
    // for (let index of treeSelect) {
    //   console.log(index);
    //   console.log(treeSelect[index].key, index)
    //
    //     ruleForm.value[treeSelect[index].key] = treeRef.value[index]!.getCheckedKeys()
    // }
    for(let i=0;i<treeSelect.length;i++){
      ruleForm.value[treeSelect[i].key] = treeRef.value[i]!.getCheckedKeys()
    }
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (props.formData.id) {
                updateData(props.model, ruleForm.value).then(({ code, data } : any) => {
                    if (code === 1) {
                        // closeEdit(formEl)
                        console.log("成功修改")
                    }
                })
            } else {
                addData(props.model, ruleForm.value).then(({ code, data } :any) => {
                    if (code === 1) {
                        // closeEdit(formEl)
                        console.log("成功新增")
                    }
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

const closeEdit = (formEl: FormInstance | undefined) => {
    console.log(formEl)
    emits("closeForm",)
}

const addObject = (key: string) => {
    // console.log(ruleForm.value[key])
    if(!ruleForm.value[key]){
        ruleForm.value[key] = {}
        // console.log(ruleForm.value[key])
    }
    // ruleForm.value[key] = {
    //     item: '111',
    //     value: '222'
    // }
    // console.log(Object.values(ruleForm.value[key]), Object.keys(ruleForm.value[key]))
    for (let i in Object.keys(ruleForm.value[key])) {
        let obj = {
            key: Object.keys(ruleForm.value[key])[i],
            value: Object.values(ruleForm.value[key])[i]
        }
        inputList.push(obj)
    }
    console.log(inputList)
    let newobj = {
        key: '',
        value: ''
    }
    inputList.push(newobj)
    // let arr = []
    // for (let i in ruleForm.value[key]) {
    //     arr.push(ruleForm.value[key][i])
    // }
    // ruleForm.value[key] = arr
    // ruleForm.value[key].push(newobj)
    // ruleForm = {
    //     value: '',
    //     key: ''
    // }
    // console.log(ruleForm)
    // obj.push(newobj)
}

const formatObject = (key: string) => {
    // console.log(key)
    // let obj = {}
    ruleForm.value[key] = {}
    inputList.map((item: any) => {
        if(item.key != ''){
            ruleForm.value[key][item.key] = item.value
        }
    })
    // ruleForm.value[key] = obj
    inputList.length = 0
    console.log(ruleForm.value[key])
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))
</script>

<style>
.treeSelectClass {
    width: 100%;
}

.rowDis_div {
    width: 90%;
}

.puting {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
}

.rowDis {
    display: flex;
    justify-content: space-between;
}
</style>